package main

import (
	"context"
	"log"
	"time"

	clientv3 "go.etcd.io/etcd/client/v3"
)

func main() {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"localhost:2379"},
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer cli.Close()
	// 申请5秒的租约
	resp, err := cli.Grant(context.TODO(), 5)
	if err != nil {
		log.Fatal(err)
	}
	// 准备1个用于取消自动续租的上下文
	ctx, cancelFunc := context.WithCancel(context.TODO())
	// 确保函数退出后，自动续租会停止
	defer cancelFunc()
	defer cli.Revoke(context.TODO(), resp.ID)

	ch, _ := cli.KeepAlive(ctx, resp.ID)
	go func() {
		for range ch {
			ka := <-ch
			if ka != nil {
				log.Println(ka.TTL)
			} else {
				log.Println("过期了")
			}
		}
	}()
	// 如果不存在key,设置
	txnResp, err := cli.Txn(context.TODO()).
		If(clientv3.Compare(clientv3.CreateRevision("/cron/lock/job9"), "=", 0)).
		Then(clientv3.OpPut("/cron/lock/job9", "1", clientv3.WithLease(resp.ID))).
		Else(clientv3.OpGet("/cron/lock/job9")).Commit()
	if err != nil {
		log.Fatal(err)
	}
	if !txnResp.Succeeded {
		log.Fatal("锁被占用", txnResp.Responses[0].GetResponseRange().Kvs[0].Value)
	}

	// 处理业务
	log.Println("处理任务")
	time.Sleep(10 * time.Second)
}
